<template>
  <view class="container">
    <!-- 搜索框 -->
    <view class="search-box" @click="goSearch">
      <view class="fake-search">
        <wd-icon name="search" size="18px" color="#999" />
        <text class="fake-search-text">搜索商品</text>
      </view>
    </view>

    <!-- 侧边栏 + 内容区 -->
    <view class="main-content">
      <!-- 侧边栏 -->
      <view class="sidebar">
       <wd-sidebar v-model="active" @change="handleTabChange">
         <wd-sidebar-item 
           v-for="item in categories" 
           :key="item.value"
           :value="item.value" 
           :label="item.label" 
         />
       </wd-sidebar>
      </view>

      <!-- 商品列表（右侧纵向排列） -->
      <scroll-view class="product-list" scroll-y>
        <view 
          v-for="(product, index) in filteredProducts" 
          :key="product.id"
          class="product-card"
          @click="handleProductClick(product)"
        >
          <image class="product-image" :src="product.image || '/static/logo.png'" mode="aspectFill" />
          <view class="product-details">
            <text class="product-name">{{ product.name }}</text>
            <view class="price-section">
              <text class="current-price">¥{{ product.price }}</text>
              <text v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</text>
            </view>
            <text class="category-tag">{{ categories.find(c => c.value === active)?.label }}</text>
          </view>
        </view>
        <!-- 无商品时显示 -->
        <view v-if="filteredProducts.length === 0" class="empty-box">
          <image src="@/img/暂无商品.svg" class="empty-img" mode="widthFix" />
          <text class="empty-text">暂无产品</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { request, BASE_URL } from '@/Requset/request'

// 搜索功能
const searchValue = ref('')
const handleSearch = (val: string) => {
  console.log('搜索:', val)
}

// 侧边栏分类数据
const categories = ref<any[]>([])
const active = ref<number | null>(null)
const products = ref<any[]>([])

// 获取商品数据
function fetchProductsByCategory(categoryId: number) {
  request({
    url: `api/getcategorygoods?category_id=${categoryId}`,
  }).then((res: any) => {
    if (Array.isArray(res.data)) {
      // 适配字段
      products.value = res.data.map(item => ({
        id: item.id,
        name: item.title,
        price: item.sell_price,
        originalPrice: item.market_price,
        image: item.thumb_path,
        category: categoryId
      }))
    } else {
      products.value = []
    }
  })
}

// 分类切换时加载对应商品
const handleTabChange = (val: any) => {
  const categoryId = typeof val === 'object' ? val.value : val
  active.value = categoryId
  console.log('切换到分类', categoryId)
  if (categoryId !== undefined) {
    fetchProductsByCategory(categoryId)
  }
}

// 获取分类数据并默认加载第一个分类商品
onMounted(() => {
  request({
    url: 'api/getcategory',
  }).then((res: any) => {
    if (Array.isArray(res.data)) {
      categories.value = res.data.map(item => ({
        value: item.id,
        label: item.title
      }))
      // 默认加载第一个分类商品
      if (categories.value.length > 0) {
        active.value = categories.value[0].value
        fetchProductsByCategory(categories.value[0].value)
      }
    }
  })
})

// 商品过滤（其实已按分类请求，这里直接返回 products 即可）
const filteredProducts = computed(() => products.value)

// 商品点击事件
function handleProductClick(product: any) {
  saveHistory(product)
  uni.navigateTo({
    url: `/pages/detail/detail?id=${product.id}`
  })
}

function saveHistory(item) {
  let history = uni.getStorageSync('history') || []
  history = history.filter(i => i.id !== item.id)
  history.unshift(item)
  if (history.length > 20) history = history.slice(0, 20)
  uni.setStorageSync('history', history)
}

function goSearch() {
  uni.navigateTo({ url: '/pages/search/search' })
}
</script>

<style scoped lang="scss">
@import '@/common/common.scss';

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.search-box {
  padding: 15rpx;
  background: #fff;
  box-shadow: 0 2rpx 4rpx rgba(0,0,0,0.05);
}

.fake-search {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 32rpx;
  padding: 0 24rpx;
  height: 64rpx;
}

.fake-search-text {
  color: #999;
  font-size: 28rpx;
  margin-left: 12rpx;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: #{px2rpx(100)};
  background: #f8f8f8;
  border-right: #{px2rpx(1)} solid #eee;
}

.product-list {
  flex: 1;
  padding: #{px2rpx(15)};
  background: #fff;
}

.product-card {
  display: flex;
  margin-bottom: #{px2rpx(15)};
  padding: #{px2rpx(12)};
  background: #fff;
  border-radius: #{px2rpx(8)};
  box-shadow: 0 #{px2rpx(2)} #{px2rpx(8)} rgba(0,0,0,0.05);
  transition: transform 0.2s;
}

.product-card:active {
  transform: scale(0.98);
}

.product-image {
  width: #{px2rpx(100)};
  height: #{px2rpx(100)};
  border-radius: #{px2rpx(6)};
  background: #f5f5f5;
}

.product-details {
  flex: 1;
  margin-left: #{px2rpx(12)};
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: #{px2rpx(15)};
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-section {
  display: flex;
  align-items: center;
  margin-top: #{px2rpx(8)};
}

.current-price {
  color: #f56c6c;
  font-size: #{px2rpx(16)};
  font-weight: bold;
}

.original-price {
  color: #999;
  font-size: #{px2rpx(12)};
  text-decoration: line-through;
  margin-left: #{px2rpx(8)};
}

.category-tag {
  align-self: flex-start;
  margin-top: #{px2rpx(8)};
  padding: #{px2rpx(2)} #{px2rpx(6)};
  background: #f0f7ff;
  color: #409eff;
  font-size: #{px2rpx(12)};
  border-radius: #{px2rpx(4)};
}

.empty-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
}

.empty-img {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}
</style>